package com.ruoyi.web.service.Impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.web.domain.mes.*;
import com.ruoyi.web.domain.vo.MaterialReturnVo;
import com.ruoyi.web.domain.vo.MaterialUseVo;
import com.ruoyi.web.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.service.IMesMaterialReturnService;

import javax.annotation.Resource;

/**
 * 物料退库Service业务层处理
 *
 * @author levicash
 * @date 2024-01-30
 */
@Service
public class MesMaterialReturnServiceImpl implements IMesMaterialReturnService {
    @Resource
    private MesMaterialReturnMapper mesMaterialReturnMapper;

    @Resource
    private MesMaterialInMapper mesMaterialInMapper;

    @Resource
    private MesMaterialMapper mesMaterialMapper;

    @Resource
    private MesMaterialMachineMapper mesMaterialMachineMapper;

    @Resource
    private MesConfigMapper configMapper;

    /**
     * 查询物料退库
     *
     * @param id 物料退库主键
     * @return 物料退库
     */
    @Override
    public MesMaterialReturn selectMesMaterialReturnById(Long id) {
        return mesMaterialReturnMapper.selectMesMaterialReturnById(id);
    }

    /**
     * 查询物料退库列表
     *
     * @param mesMaterialReturn 物料退库
     * @return 物料退库
     */
    @Override
    public List<MesMaterialReturn> selectMesMaterialReturnList(MesMaterialReturn mesMaterialReturn) {
        return mesMaterialReturnMapper.selectMesMaterialReturnList(mesMaterialReturn);
    }

    /**
     * 新增物料退库
     *
     * @param mesMaterialReturn 物料退库
     * @return 结果
     */
    @Transactional
    @Override
    public int insertMesMaterialReturn(MesMaterialReturn mesMaterialReturn) {
        mesMaterialReturn.setCreateBy(SecurityUtils.getUsername());
        mesMaterialReturn.setCreateTime(DateUtils.getNowDate());
        // 生成退库单编号
        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "code");
        map.put("tableName", "mes_material_return");
        int maxNum = configMapper.getMaxId(map);
        String code = PinYinUtils.getCodeNormal(maxNum, "WLTKD");
        mesMaterialReturn.setCode(code);
        int rows = mesMaterialReturnMapper.insertMesMaterialReturn(mesMaterialReturn);
        insertMesMaterialReturndetail(mesMaterialReturn);
        return rows;
    }

    /**
     * 修改物料退库
     *
     * @param mesMaterialReturn 物料退库
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMesMaterialReturn(MesMaterialReturn mesMaterialReturn) {
        mesMaterialReturn.setUpdateTime(DateUtils.getNowDate());
        mesMaterialReturn.setUpdateBy(SecurityUtils.getUsername());
        int status = mesMaterialReturn.getStatus();
        if (status == 1) {// 提交
            // 修改物料入库明细的仓库数量(加库存)
            MesMaterialReturn Info = mesMaterialReturnMapper.selectMesMaterialReturnById(mesMaterialReturn.getId()); // 查询数据库
            List<MesMaterialReturndetail> mesMaterialReturndetailList = Info.getMesMaterialReturndetailList();
            if (mesMaterialReturndetailList.size() > 0) {
                // 获取关联ids
                List<Long> listId = mesMaterialReturndetailList.stream().map(it -> it.getMaterialId()).collect(Collectors.toList());
                Long[] ids = listId.toArray(new Long[0]);
                // 根据关联ids查询物料明细
                List<MesMaterial> detailList = mesMaterialMapper.selectMesMaterialByIds(ids);
                // 遍历明细修改库存
                for (MesMaterialReturndetail mesMaterialReturndetail : mesMaterialReturndetailList) {
                    for (MesMaterial detailItem : detailList) {
                        if (detailItem.getId().equals(mesMaterialReturndetail.getMaterialId())) {

                            BigDecimal stockNum = (detailItem.getQuantity() == null ? BigDecimal.ZERO : detailItem.getQuantity()); // 库存数量
                            BigDecimal quantity = mesMaterialReturndetail.getQuantity(); // 退库数量
                            //Start 20240407 应该去比较机台库存数量
                           // int result = stockNum.compareTo(quantity);
                            MesMaterialMachine mesMaterialMachine = new MesMaterialMachine();
                            mesMaterialMachine.setMaterialId(detailItem.getId());
                            mesMaterialMachine.setMachineId(mesMaterialReturn.getMachineId());
                            List<MesMaterialMachine> listMaterialMachine = mesMaterialMachineMapper.selectMesMaterialMachineList(mesMaterialMachine);
                            BigDecimal machineStock=BigDecimal.ZERO;//机台库存
                            if (listMaterialMachine.size() > 0) {
                                 machineStock = listMaterialMachine.get(0).getMachineStock();
                            }
                            int result = machineStock.compareTo(quantity);
                            //End
                            if (result < 0) {
                                throw new ServiceException("退库数量大于库存数量！");
                            } else {
                                BigDecimal difference = stockNum.add(quantity);
                                detailItem.setQuantity(difference);         // 更改库存数量
                                detailItem.setStockPrice(difference.multiply(detailItem.getRealtimePrice()));  // 更改金额

                                // 新增或者修改(存在更新不存在新增),物料库存机台库存关联表中物料对应的机台数量
                                //Start 20240407 提到前面去
//                                MesMaterialMachine mesMaterialMachine = new MesMaterialMachine();
//                                mesMaterialMachine.setMaterialId(detailItem.getId());
//                                mesMaterialMachine.setMachineId(mesMaterialReturn.getMachineId());
//                                List<MesMaterialMachine> listMaterialMachine = mesMaterialMachineMapper.selectMesMaterialMachineList(mesMaterialMachine);
                                //End
                                if (listMaterialMachine.size() > 0) {
                                     machineStock = listMaterialMachine.get(0).getMachineStock();
                                    BigDecimal temp = machineStock.subtract(quantity);
                                    mesMaterialMachine.setMachineStock(temp);
                                    mesMaterialMachine.setId(listMaterialMachine.get(0).getId());
                                    mesMaterialMachineMapper.updateMesMaterialMachine(mesMaterialMachine);
                                }
                            }
                        }
                    }
                }
                // 批量修改物料明细库存
                mesMaterialMapper.updateStockNumByBatch(detailList);
            }
        } else {
            mesMaterialReturnMapper.deleteMesMaterialReturndetailByMaterialuseId(mesMaterialReturn.getId());
            insertMesMaterialReturndetail(mesMaterialReturn);
        }

        return mesMaterialReturnMapper.updateMesMaterialReturn(mesMaterialReturn);
    }

    /**
     * 批量删除物料退库
     *
     * @param ids 需要删除的物料退库主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesMaterialReturnByIds(Long[] ids) {
        mesMaterialReturnMapper.deleteMesMaterialReturndetailByMaterialuseIds(ids);
        return mesMaterialReturnMapper.deleteMesMaterialReturnByIds(ids);
    }

    /**
     * 删除物料退库信息
     *
     * @param id 物料退库主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesMaterialReturnById(Long id) {
        mesMaterialReturnMapper.deleteMesMaterialReturndetailByMaterialuseId(id);
        return mesMaterialReturnMapper.deleteMesMaterialReturnById(id);
    }

    /**
     * 新增物料退库明细信息
     *
     * @param mesMaterialReturn 物料退库对象
     */
    public void insertMesMaterialReturndetail(MesMaterialReturn mesMaterialReturn) {
        List<MesMaterialReturndetail> mesMaterialReturndetailList = mesMaterialReturn.getMesMaterialReturndetailList();
        Long id = mesMaterialReturn.getId();
        if (StringUtils.isNotNull(mesMaterialReturndetailList)) {
            List<MesMaterialReturndetail> list = new ArrayList<MesMaterialReturndetail>();
            for (MesMaterialReturndetail mesMaterialReturndetail : mesMaterialReturndetailList) {
                mesMaterialReturndetail.setCreateBy(SecurityUtils.getUsername());
                mesMaterialReturndetail.setCreateTime(DateUtils.getNowDate());
                mesMaterialReturndetail.setMaterialreturnId(id);
                list.add(mesMaterialReturndetail);
            }
            if (list.size() > 0) {
                mesMaterialReturnMapper.batchMesMaterialReturndetail(list);
            }
        }
    }

    /**
     * 查询物料退库明细
     *
     * @param map 查询参数
     * @return 物料退库关联集合
     */
    @Override
    public List<MaterialReturnVo> selectMesMaterialReturnDetailList(Map<String, Object> map) {
        return mesMaterialReturnMapper.selectMesMaterialReturnDetailList(map);
    }
}
